package com.yang.eduauth.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.commonutils.R;
import com.yang.eduauth.entity.*;
import com.yang.eduauth.service.*;
import com.yang.eduauth.utils.JwtUtils;
import com.yang.eduauth.vo.PermissionVo;
import com.yang.eduauth.vo.UserQuery;
import com.yang.eduauth.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yds
 * @since 2020-12-16
 */

@RestController
@RequestMapping("/eduauth/user")
@Api(description = "基础登陆管理")
@CrossOrigin
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    RolePermissionService rolePermissionService;


    /**
     * 获取所有讲师
     * @return
     */
    @ApiOperation("查询所有用户")
    @GetMapping("/findAll")
    public R findAllTeather(){
        List<User> list = userService.list(null);
        return R.ok().data("items",list);
    }

    /**
     * 逻辑删除讲师
     * @param id
     * @return
     */
    @ApiOperation("逻辑删除讲师")
    @DeleteMapping("/{id}")
    public R removeTeacher(@ApiParam(name="id",value="讲师id",required = true)
                           @PathVariable String id){
        boolean flag = userService.removeById(id);
        return flag?R.ok():R.error();

    }

    @ApiOperation("分页查询用户")
    @GetMapping("/pageUser/{current}/{limit}")
    public R pageListTeacher(@ApiParam(name="current",value="当前页",required = true)
                             @PathVariable long current,
                             @ApiParam(name="limit",value="每页数据",required = true)
                             @PathVariable long limit){

        //创建page对象
        Page<User> pageUser=new Page<User>(current,limit);
        userService.page(pageUser, null);
        long total = pageUser.getTotal();
        List<User> records = pageUser.getRecords();
        Map map=new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return R.ok().data(map);

    }

    /***
     * 条件分页查询
     * @param current
     * @param limit
     * @param userQuery
     * @RequestBody 将post请求的json分装到注解对应的实体里
     * @return
     */
    @ApiOperation("用户条件查询分页")
    @PostMapping("/pageUserCondition/{current}/{limit}")
    public R pageTeacherCondition(@ApiParam(name="current",value="当前页",required = true)
                                  @PathVariable long current,
                                  @ApiParam(name="limit",value="每页数据",required = true)
                                  @PathVariable long limit,
                                  @RequestBody(required = false) UserQuery userQuery){
        //创建page对象
        Page<User> pageUser=new Page<User>(current,limit);
        QueryWrapper<User> wrapper=new QueryWrapper<User>();
        String name = userQuery.getName();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        IPage<User> page = userService.page(pageUser, wrapper);
        long total = pageUser.getTotal();
        List<User> records = pageUser.getRecords();
        Map map=new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return R.ok().data(map);

    }
    @ApiOperation("增加用户接口")
    @PostMapping("/addUser")
    public R addTeacher(@RequestBody User user){
        boolean save = userService.save(user);
        return save?R.ok():R.error();
    }
    @ApiOperation("根据id获取用户信息")
    @GetMapping("/getUser/{id}")
    public R getTeacher(@PathVariable String id){
        User user = userService.getById(id);
        return R.ok().data("item",user);
    }
    @ApiOperation("修改用户信息")
    @PostMapping("/updateUser")
    public R updateTeacher(@RequestBody User user){
        boolean b = userService.updateById(user);
        return b?R.ok():R.error();
    }



    @GetMapping("/enter/{appCode}/{roleId}")
    @ApiOperation("用户应用登陆")
    public R enterApp(@PathVariable("appCode") String appCode, @PathVariable("roleId") String roleId){
        QueryWrapper<RolePermission> rPWrapper = new QueryWrapper();
        List<PermissionVo> list = new ArrayList<>();

            rPWrapper.eq("role_id","1");

            List<RolePermission> pList = rolePermissionService.list(rPWrapper);

            for (RolePermission item : pList) {
                String permissionId = item.getPermissionId();
                Permission permission = permissionService.getById(permissionId);
                PermissionVo permissionVo = new PermissionVo();
                Map<String,String> map=new HashMap<>();
                map.put("icon",permission.getIcon());
                map.put("title",permission.getName());
                String component="Layout";
                if(permission.getType().equals("C")){
                    component=permission.getComponent();
                }
                permissionVo.setId(permission.getId())
                        .setName(permission.getName())
                        .setHidden(permission.getStatus().equals("1")?true:false)
                        .setPid(permission.getPid())
                        .setPath(permission.getPath())
                        .setMeta(map)
                        .setComponent(component);
                list.add(permissionVo);

            }

        final List<PermissionVo> menus = list.stream().filter(l -> !l.getHidden())
                .collect(Collectors.toList());
        List<PermissionVo> firstLevel = menus.stream().filter(p -> p.getPid().equals("0")).collect(Collectors.toList());
        firstLevel.parallelStream().forEach(m -> {
            setChild(m, menus);
        });
        return R.ok().data("token","").data("Authorization","admin").data("role","派发员").data("menus",firstLevel);

    };

    @GetMapping("/login/{username}/{password}")
    @ApiOperation("用户登陆")
    public R login(@PathVariable("username") String account, @PathVariable("password") String password){
        UserVo uv=new UserVo();
        QueryWrapper<User> userWrapper=new QueryWrapper();
        userWrapper.eq("account",account);
        User user = userService.getOne(userWrapper);
        String id = user.getId();
        QueryWrapper<UserRole> userRoleWrapper=new QueryWrapper();
        userRoleWrapper.eq("user_id",id);
        List<UserRole> list = userRoleService.list(userRoleWrapper);
        List<Role> rList = new ArrayList<Role>();
        Set<String> apps = new HashSet<String>(10);
        for(UserRole item:list){
            String roleId = item.getRoleId();
            Role role = roleService.getById(roleId);
            apps.add(role.getAppCode());
            rList.add(role);
        }
        uv.setAccount(account);
        uv.setId(id);
        uv.setRoles(rList);
        uv.setApps(apps);
        JwtUtils util=new JwtUtils();
        String jwtToken = util.getJwtToken(id, uv);
        System.out.println(uv.toString());
        return R.ok().data("token",jwtToken).data("Authorization","admin").data("role","派发员").data("menus","");
    };

    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public R login(){
        return R.ok().data("token","");
    };


    /**
     * 设置子元素
     *
     * @param m
     * @param menus
     */
    private void setChild(PermissionVo m, List<PermissionVo> menus) {
        Set<PermissionVo> child = menus.parallelStream().filter(a -> a.getPid().equals(m.getId())).collect(Collectors.toSet());
        m.setChildren(child);
        if (!CollectionUtils.isEmpty(child)) {
            child.parallelStream().forEach(c -> {
                //递归设置子元素，多级菜单支持
                setChild(c, menus);
            });
        }
    }

    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public R info(){
        QueryWrapper<RolePermission> rPWrapper = new QueryWrapper();
        List<PermissionVo> list = new ArrayList<>();

        rPWrapper.eq("role_id","5");

        List<RolePermission> pList = rolePermissionService.list(rPWrapper);

        for (RolePermission item : pList) {
            String permissionId = item.getPermissionId();
            Permission permission = permissionService.getById(permissionId);
            PermissionVo permissionVo = new PermissionVo();
            Map<String,String> map=new HashMap<>();
            map.put("icon",permission.getIcon());
            map.put("title",permission.getName());
            String component="Layout";
            if(permission.getType().equals("C")){
                component=permission.getComponent();
            }
            permissionVo.setId(permission.getId())
                    .setName(permission.getName())
                    .setHidden(permission.getStatus().equals("1")?true:false)
                    .setPid(permission.getPid())
                    .setPath(permission.getPath())
                    .setMeta(map)
                    .setComponent(component);
            list.add(permissionVo);

        }

        final List<PermissionVo> menus = list.stream().filter(l -> !l.getHidden())
                .collect(Collectors.toList());
        List<PermissionVo> firstLevel = menus.stream().filter(p -> p.getPid().equals("0")).collect(Collectors.toList());
        firstLevel.parallelStream().forEach(m -> {
            setChild(m, menus);
        });
        return R.ok().data("roles","[admin]")
                .data("name","admin")
                .data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif")
                .data("menu",firstLevel);
    }



}

